package cn.lg.soar.mvc.model;

import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 用于feign文件传输
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class MultipartFileDTO implements MultipartFile {
	private final String name;
	private final String originalFilename;
	@Nullable
	private final String contentType;
	private final byte[] content;

	public MultipartFileDTO(String name, @Nullable byte[] content) {
		this(name, "", (String)null, (byte[])content);
	}

	public MultipartFileDTO(String name, InputStream contentStream) throws IOException {
		this(name, "", (String)null, (byte[]) FileCopyUtils.copyToByteArray(contentStream));
	}

	public MultipartFileDTO(String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {
		Assert.hasLength(name, "Name must not be empty");
		this.name = name;
		this.originalFilename = originalFilename != null ? originalFilename : "";
		this.contentType = contentType;
		this.content = content != null ? content : new byte[0];
	}

	public MultipartFileDTO(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException {
		this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
	}

	public MultipartFileDTO(Path path) {
		this.name = path.getFileName().toString();
		this.originalFilename = this.name;
		try {
			this.contentType = Files.probeContentType(path);
			this.content = Files.readAllBytes(path);;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public String getName() {
		return this.name;
	}

	@NonNull
	public String getOriginalFilename() {
		return this.originalFilename;
	}

	@Nullable
	public String getContentType() {
		return this.contentType;
	}

	public boolean isEmpty() {
		return this.content.length == 0;
	}

	public long getSize() {
		return (long)this.content.length;
	}

	public byte[] getBytes() throws IOException {
		return this.content;
	}

	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(this.content);
	}

	public void transferTo(File dest) throws IOException, IllegalStateException {
		FileCopyUtils.copy(this.content, dest);
	}
}